<?php
namespace app\app\controller\v1;
use app\app\model\Users;
use app\app\model\Orders;
use think\Request;
use app\app\util\OnlineUtils;

class UserController extends BaseController{

	/**
	 * [UserCenter 个人中心]
	 * 	
	 */
	public function UserCenter()
	{
		$user_id   = OnlineUtils::getUserIdBySid();
		//实例化User对象
		$user = new Users();
		$user->user_id = $user_id;
		$userinfo = $user->getInfo();
		//待付款
		$Order= new Orders($user_id);
		$order_unpaid = $Order->getUnpaid();
		$data = array('unpaid_order'=>$order_unpaid,'userinfo'=>$userinfo);
		//返回数据
		return jsonReturn(200,'success',$data);		
	}

    //企业付款
    public function EnterprisePay()
    {
        $user_id = OnlineUtils::getUserIdBySid();
        $time = "2018-07-16 00-00-00";
        $now  = date('Y-m-d H:i:s',time());
		if($user_id != 1){
			if($now < $time){
				return wc(402,'活动期间无法进行提现');
			}			
		}
        $user = Db::name('user')->where('id','eq',$user_id)->where('status','eq',1)->find();
        $openid = $user['open_id'];
        //下单
        $order['uid'] = $user_id;
        //生成唯一订单号
        $order['order_number'] = OnlyOneOrderNumber();
        $fee = input('post.fee') ? input('post.fee') : 0;  
        //费用
        $total_fee = $user['fee']/100;
        if($fee > $total_fee){
            return wc(402,'账户余额不足');
        }
		if($fee == 0){
			return wc(402,'提现金额不能为0');
		}
        //订单费用
        $order['total_fee'] = $fee*100;        
        //订单生成时间
        $order['create_time'] = date('Y-m-d H:i:s',time());
        //插入表
        $order_id = Db::name('withdraw')->insertGetId($order);
        //查询订单表
        $orders = Db::name('withdraw')->where('id','eq',$order_id)->where('status','eq',1)->find();
        $order_number = $orders['order_number'];
        $total_fee = $orders['total_fee'];
        //描述
        $desc = "爱看世界杯提现付款";
        $data = array(
            'mch_appid' => config('MCH_APPID'),
            'mchid'     => config('MCH_ID'),
            'partner_trade_no'=> $order_number,
            'amount'    => intval($total_fee),
            'openid'    => $openid,
            'check_name'=> 'NO_CHECK',
            'desc'      => $desc,
            'spbill_create_ip'=> $_SERVER["REMOTE_ADDR"],
        );
        $post_data = $this->setSendData($data);
        // return wc(200,'success',$post_data);
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        // return wc(200,'success',$cert);
        $xml_data = $this->senXml($url,$post_data);
        // return wc(200,'success',$xml_data);
       //解析返回数据
        $postObj = $this->xmlToObject($xml_data);
		if($postObj->result_code == "FAIL"){
			return wc(402,'fail',$postObj->err_code_des);
		}else{
			//减少用户余额
			Db::query('update wc_user set fee = fee - '.intval($fee*100).' where id ='.$user_id);
			//修改提现表
			$time = date('Y-m-d H:i:s',time());
			Db::query('update wc_withdraw set pay_time = "'.$time.'",status = 2 where id ='.$order_id);
			return wc(200,'success','提现成功,快去我的零钱查看吧');
		}
    }


    /**
     * 拼装请求的数据
     * @return  String 拼装完成的数据
     */
    private function setSendData($data) {
        $sTpl = "<xml>
                    <mch_appid><![CDATA[%s]]></mch_appid>
                    <mchid><![CDATA[%s]]></mchid>
                    <nonce_str><![CDATA[%s]]></nonce_str>
                    <partner_trade_no><![CDATA[%s]]></partner_trade_no>
                    <openid><![CDATA[%s]]></openid>
                    <check_name><![CDATA[%s]]></check_name>
                    <amount><![CDATA[%s]]></amount>
                    <desc><![CDATA[%s]]></desc>
                    <spbill_create_ip><![CDATA[%s]]></spbill_create_ip>
                    <sign><![CDATA[%s]]></sign> 
                </xml>";                          //xml数据模板

        //随机数
        $nonce_str = $this->getNonceStr();
        //异步通知地址
        $notify_url = config('WX_NOTIFY_URL');
        //将要发送的信息数组
        $data['nonce_str'] = $nonce_str;
        // 注意：以上几个参数是追加到$data中的，$data中应该同时包含开发文档中要求必填的剔除sign以外的所有数据
        $sign = $this->getSign($data);      //获取签名
        //替换成xml数据
        $data = sprintf($sTpl, $data['mch_appid'], $data['mchid'], $nonce_str, $data['partner_trade_no'],$data['openid'], $data['check_name'], $data['amount'], $data['desc'], $data['spbill_create_ip'], $sign);
        return $data;
    }

    //发送post请求(xml数据)
    private function senXml($url,$xmlData)
    {
        $header[] = "Content-type: text/xml"; //定义content-type为xml,注意是数组
        //初始化
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT,30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS, $xmlData);
        //使用证书：cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/cert/apiclient_cert.pem');
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/cert/apiclient_key.pem');
        //请求结果
        $response = curl_exec($ch);
        //返回错误
        if(curl_errno($ch)){
            print(curl_error($ch));
        }
        curl_close($ch);
        return $response;
    }


    /**
     * 生成随机数并返回
     */
    private function getNonceStr() {
        $code = "";
        for ($i=0; $i > 10; $i++) { 
            $code .= mt_rand(1000);        //获取随机数
        }
        $nonceStrTemp = md5($code);
        $nonce_str = mb_substr($nonceStrTemp, 5,37);      //MD5加密后截取32位字符
        return $nonce_str;
    }

    /**
     * 获取参数签名；
     * @param  Array  要传递的参数数组
     * @return String 通过计算得到的签名；
     */
    private function getSign($params) {
        ksort($params);        //将参数数组按照参数名ASCII码从小到大排序
        foreach ($params as $key => $item) {
            if (!empty($item)) {         //剔除参数值为空的参数
                $newArr[] = $key.'='.$item;     // 整合新的参数数组
            }
        }
        $stringA = implode("&", $newArr);         //使用 & 符号连接参数
        $stringSignTemp = $stringA."&key=".config('WX_APP_KEY');        //拼接key
                                             // key是在商户平台API安全里自己设置的
        $stringSignTemp = MD5($stringSignTemp);       //将字符串进行MD5加密
        $sign = strtoupper($stringSignTemp);      //将所有字符转换为大写
        return $sign;
    }



    /**
     * 解析xml文档，转化为对象
     * @param  String $xmlStr xml文档
     * @return Object         返回Obj对象
     */
    private function xmlToObject($xmlStr) {
        if (!is_string($xmlStr) || empty($xmlStr)) {
            return false;
        }
        // 由于解析xml的时候，即使被解析的变量为空，依然不会报错，会返回一个空的对象，所以，我们这里做了处理，当被解析的变量不是字符串，或者该变量为空，直接返回false
        $postObj = simplexml_load_string($xmlStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $postObj = json_decode(json_encode($postObj));
        //将xml数据转换成对象返回
        return $postObj;
    }


    //回调地址
    public function notifyUrl()
    {
        return hmp(200,'success');    
    }

}